package leecode.q39;

import java.util.ArrayList;
import java.util.List;

/**
 * 2021年8月16日23:59:20 开始
 * 2021年8月17日00:12:18 结束
 */
public class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> list = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        traceBack(candidates, target);
        return res;
    }

    private void traceBack(int[] candidates, int target) {
        if (sum(list) > target || isDup(list)) {
            return;
        }
        if (sum(list) == target) {
            res.add(new ArrayList<>(list));
        }
        for (int cur : candidates) {
            list.add(cur);
            traceBack(candidates, target);
            list.remove(list.size() - 1);
        }
    }

    private boolean isDup(List<Integer> list) {
        if (list.size() <= 1) {
            return false;
        }
        return list.get(list.size() - 1) < list.get(list.size() - 2);
    }

    private int sum(List<Integer> list) {
        int sum = 0;
        for (Integer integer : list) {
            sum += integer;
        }
        return sum;
    }
}
